<template>
  <div class="form">
    <input v-model="formData.text" placeholder="Type here">
    <p>Text: {{ formData.text }}</p>

    <input v-model="formData.email" placeholder="Email">
    <p>Email: {{ formData.email }}</p>

    <input v-model="formData.age" type="number" placeholder="Age">
    <p>Age: {{ formData.age }}</p>

    <label>
      <input v-model="formData.agree" type="checkbox">
      Agree to terms
    </label>
    <p>Agree: {{ formData.agree }}</p>

    <div>
      <label>
        <input v-model="formData.gender" type="radio" value="male">
        Male
      </label>
      <label>
        <input v-model="formData.gender" type="radio" value="female">
        Female
      </label>
      <label>
        <input v-model="formData.gender" type="radio" value="other">
        Other
      </label>
    </div>
    <p>Gender: {{ formData.gender }}</p>

    <button @click="submitForm">Submit</button>
    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const formData = ref({
  text: '',
  email: '',
  age: '',
  agree: false,
  gender: ''
})

const errorMessage = ref('')

const isRequired = computed(() => formData.value.text.trim() !== '')
const isLengthValid = computed(() => formData.value.text.length >= 3 && formData.value.text.length <= 20)
const isValidEmail = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(formData.value.email);
})

const validate = () => {
  errorMessage.value = '';

  if (!isRequired.value) {
    errorMessage.value = 'Text field is required';
  } else if (!isLengthValid.value) {
    errorMessage.value = 'Text length must be between 3 and 20 characters';
  } else if (!isValidEmail.value) {
    errorMessage.value = 'Please enter a valid email address';
  } else if (!formData.value.agree) {
    errorMessage.value = 'You must agree to the terms';
  } else if (!formData.value.gender) {
    errorMessage.value = 'Please select a gender';
  }
}

const submitForm = () => {
  validate();
  if (!errorMessage.value) {
    alert('Form submitted successfully!');
  }
}
</script>

<style scoped>
.form {
  text-align: center;
  margin-top: 20px;
}

input {
  padding: 10px;
  width: 200px;
  margin-bottom: 10px;
}

button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #35a56a;
}

.error-message {
  color: red;
  font-weight: bold;
  margin-top: 10px;
}

label {
  display: block;
  margin: 5px 0;
}
</style>